package UMC.Data;


import UMC.Web.WebMeta;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.UUID;

/**
 * Web资源管理器，可以在App_Data/UMC/assembly.xml中注册
 */
public class WebResource extends DataProvider {


    public static final String ImageResource = "~/images/";

    public static final String UserResources = "~/UserResources/";
    static WebResource _Instance;

    public static WebResource Instance() {
        if (_Instance == null) {
            ProviderConfiguration pc = ProviderConfiguration.configuration("assembly");
            if (pc != null) {
                Provider provider = pc.get("WebResource");
                if (provider != null) {
                    _Instance = (WebResource) Utility.createInstance(provider);
                    if (_Instance == null) {
                        _Instance = new WebResource();
                        _Instance.provider = provider;
                    }
                }
            }
            if (_Instance == null) {
                _Instance = new WebResource();
                _Instance.provider = Provider.create("WebResource", "UMC.Data.WebResource");
            }
        }
        return _Instance;
    }


    public static void Instance(WebResource webResource, Provider provider) {
        webResource._Provider = provider;
        _Instance = webResource;
    }

    UMC.Data.Provider _Provider;

    public UMC.Data.Provider getProvider() {
        return _Provider;

    }

    public String WebDomain() {
        return Utility.isNull(_Provider.get("domain"), "localhost");
    }

    public String ImageResolve(URI uri, Object id, Object key, Object size) {
        return ImageResolve(uri, id, key, size, "");
    }

    public String ImageResolve(URI uri, Object id, Object key, Object size, String cache) {
        String AbsolutePath = ImageResolve(id.toString(), key, size, cache);
        if (AbsolutePath.startsWith("http://") || AbsolutePath.startsWith("https://")) {
            return AbsolutePath;
        } else {
            return String.format("%s://%s%s", uri.getScheme(), uri.getAuthority(), AbsolutePath);
        }
    }

    protected String ImageResolve(String id, Object key, Object size, String cache) {
        String kdey = "";
        switch (size.toString()) {
            case "0":
                return ResolveUrl(String.format("%s%s/%s/0.png?%s", ImageResource, id, key, cache));
            case "1":
                kdey = "m350";
                break;
            case "2":
                kdey = "m200";
                break;
            case "3":
                kdey = "m150";
                break;
            case "4":
                kdey = "m100";
                break;
            case "5":
                kdey = "m50";
                break;
            case "-3":
                kdey = "m200x140";
                break;
            case "-1":
                kdey = "m350x200";
                break;
            case "-4":
                kdey = "m400x100";
                break;
            case "-2":
                kdey = "m200x100";
                break;
        }
        return ResolveUrl(String.format("%s%s/%s/0.png?umc-image=%s&%s", ImageResource, id, key, kdey, cache));

    }

    public void Transfer(InputStream stream, String targetKey) {
        if (targetKey.startsWith("UserResources/") || targetKey.startsWith("images/")) {
            Utility.copy(stream, Utility.mapPath("Static/" + targetKey));
        } else if (targetKey.indexOf('.') == -1) {
            Utility.copy(stream, Utility.mapPath("Static/" + targetKey + ".html"));

        }
    }

    public void Transfer(URI soureUrl, String targetKey) {
        if (targetKey.startsWith("bin/")) {
            return;
        } else if (targetKey.startsWith("app_data/")) {
            return;
        }
        switch (soureUrl.getScheme()) {
            case "file":
                File file = new File(soureUrl.getPath());//.replace('/', System.IO.Path.DirectorySeparatorChar);
//                FileInputStream is = null;
                if (file.isFile() && file.exists()) {
                    try {
                        Utility.copy(new FileInputStream(file), targetKey);
//
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }
//
                break;
            default:
                HttpURLConnection connection = null;
                try {
                    connection = (HttpURLConnection) soureUrl.toURL().openConnection();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                try {
                    connection.connect();
                    if (connection.getResponseCode() == 200) {
                        InputStream is = connection.getInputStream();
                        Utility.copy(connection.getInputStream(), targetKey);

                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                break;
        }

    }

    public String ResolveUrl(URI uri, String path) {
        // UriBuilder
        String AbsolutePath = ResolveUrl(path);
        if (AbsolutePath.startsWith("http://") || AbsolutePath.startsWith("https://")) {
            return AbsolutePath;
        } else {
            return String.format("%s://%s%s", uri.getScheme(), uri.getAuthority(), AbsolutePath);
        }
    }

    public String ResolveUrl(String path) {
        String vUrl = path;
        if (path.startsWith("~/")) {
            vUrl = path.substring(1);
        } else if (path.startsWith("~")) {
            vUrl = "/" + path.substring(1);
        }
        return vUrl;
    }

    public void Transfer(URI uri, Object guid, Object seq, String type) {
        String key = String.format("images/%s/%s/%s.%s", guid, seq, 0, type.toLowerCase());
        Transfer(uri, key);
    }

    public void Transfer(URI uri, Object guid, Object seq) {
        Transfer(uri, guid, seq, "png");
    }

}